package bcpay

import (
	"context"
	"errors"
	"fmt"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/xerrors"
	"github.com/bytedance/sonic"
	"github.com/bytedance/sonic/decoder"
)

type Factory struct {
}

func (p *Factory) CreatePay(config base.Config) base.Payment {
	return &Bcpay{
		Url:       config.Url,
		AppId:     config.AppId,
		SecretKey: config.SecretKey,
		ReturnUrl: config.ReturnUrl,
		NotifyUrl: config.NotifyUrl,
	}
}

type Bcpay struct {
	AppId     string
	SecretKey string
	Url       string
	ReturnUrl string
	NotifyUrl string
}

type Resp struct {
	Code  int64  `json:"code"`
	Msg   string `json:"msg"`
	Error string `json:"error"`
	Data  any    `json:"data"`
}

// 代收订单创建
func (bc *Bcpay) Pay(ctx context.Context, req map[string]any) (resp base.PayResponse, err error) {
	// 请求第三方接口
	url := bc.Url + "/payment/order/create"
	params := make(map[string]any)
	params["appId"] = bc.AppId
	params["merOrderNo"] = req["orderNo"]
	params["currency"] = "BRL"
	params["amount"] = fmt.Sprintf("%.2f", req["amount"])
	params["returnUrl"] = bc.ReturnUrl
	params["notifyUrl"] = bc.NotifyUrl
	params["sign"] = GenerateSign(params, bc.SecretKey)
	result, err := sendRequest(ctx, url, params)
	if err != nil {
		return
	}

	// 验签
	sign := GenerateSign(result.Data.(map[string]any), bc.SecretKey)
	if sign != result.Data.(map[string]any)["sign"] {
		return resp, xerrors.ErrSignVerifyFailed
	}

	// 处理返回参数 params 字段
	rp := make(map[string]any)
	if err = sonic.Unmarshal([]byte(result.Data.(map[string]any)["params"].(string)), &rp); err != nil {
		return
	}

	resp = base.PayResponse{
		Url:     rp["url"].(string),
		QrCode:  rp["qrcode"].(string),
		OrderNo: result.Data.(map[string]any)["orderNo"].(string),
	}
	return
}

// 发送请求
func sendRequest(ctx context.Context, url string, params map[string]any) (resp Resp, err error) {
	output, err := base.SendPostJson(ctx, url, params)
	if err != nil {
		return resp, err
	}
	dc := decoder.NewDecoder(output)
	dc.UseNumber()
	dc.Decode(&resp)
	if resp.Code != 0 {
		return resp, errors.New(resp.Msg)
	}
	return
}
